<?php

namespace app\jxcshop\controller\api;

use app\ApiController;
use app\distribution\model\DistributionJcLog;
use app\distribution\model\DistributionLog;
use app\distribution\model\DividendAwardModel;
use app\distribution\model\DividendModel;
use app\member\model\AccountModel;
use app\member\model\UsersLevelApplyModel;
use app\member\model\UsersModel;
use app\jxcshop\model\OrderGoodsModel;
use app\jxcshop\model\OrderModel;
use app\jxcshop\model\SlideModel;
use app\jxcshop\model\GoodsModel;
use app\jxcshop\model\NavMenuModel;
use distribution\base\Dividend;
use think\Db;
use think\Exception;
use app\jxcshop\model\JiaquanfenhongJc;

class Index extends ApiController
{

    public function getJcList()
    {
        $list =UsersLevelApplyModel::where('num','>',0)->select();
        return $this->success('','',$list);
    }
    public function Income(){

        $where =[
            'jiaquanfenhong_log.stage'=>date('Ym'),
        ];
        $list =(new JiaquanfenhongJc())->alias('jiaquanfenhong_log')->where($where)->join('shop_goods_jxc g','g.goods_id=jiaquanfenhong_log.goods_id')
            ->field('jiaquanfenhong_log.*,g.goods_name')
            ->order('id desc')
            ->select();

        foreach ($list as $k=>$v){
            $list[$k]['enter_amount'] = round($v['enter_amount'],2);
        }

        return $this->success('','',$list);
    }
    public function getJcInfo(){

        $jc = Db::table("jiaquanfenhong_log")->where("1=1")->select();
        $where =[
            'user_id'=>$this->userInfo['user_id'],
            'stage'=>date('Ym'),
        ];
        //$user = UsersModel::where(['user_id' => $this->userInfo['user_id']])->find();
        $wherejc =[
            'stage'=>date('Ym'),
            'isstatus' => 0,
        ];
        $yujifenhong = Db::table("jiaquanfenhong_jc")->where($wherejc)->sum('enter_amount');
//        $gd_count = Db::table("users")->where(['jxcshopgudong' => 1])->count();
//        $yujifenhong = round($yujifenhong / $gd_count,2);
        $pushCount = Db::table("users")->where(['jxcshopgudong' => 1])->count();

        $divAmount = intval($yujifenhong / $pushCount);

        $list = Db::table("jiaquanfenhong_log")->where($where)->select();

        unset($where['stage']);
        $total_amount = Db::table("jiaquanfenhong_log")->where($where)->sum('total_amount');
        $is_gd = Db::table("users")->where(['jxcshopgudong' => 1,'user_id'=>$this->userInfo['user_id']])->count();
        if(!$is_gd){
            $yujifenhong = 0;
        }
        $data =['list'=>$list,'divAmount'=>$divAmount,'total_amount'=>$total_amount,'info'=>$yujifenhong];
        return $this->success('','',$data);
    }

    public function rubfk()
    {


        $upUser = UsersModel::where(['user_id' => 29945])->find();
        rubQr();die;
        if ($upUser['role_id'] == 3 || $upUser['role_id'] == 0) {
            //$pid = 0;
            do {
                //if (empty($upUser['pid'])) break;
                $parentId=$upUser['pid'];

                $upUser = UsersModel::where(['user_id' => $upUser['pid'], 'role_id' => 1])
                    ->field('role_id,user_id,pid')->find();
                if(!empty($upUser['pid'])){
                    $parentId = $upUser['user_id'];
                }
            } while ($parentId > 0);
        }
        die;

        $orderInfo = OrderModel::where(['order_sn'=>2023022447314])->find();
        halt((new OrderModel())->distribution($orderInfo, 'add'));
        //halt((new OrderModel())->distribution($orderInfo, 'add'));


        $userMode = new UsersModel();
        $parentId = 29944;
        $goods = GoodsModel::find(38);
        $goods['award_value'] = json_decode($goods['award_value'], true);
        $dailicount = 0;

        do {
            $nowLevel++;
            $userInfo = $userMode->info($parentId); //获取会员信息
            $parentId = $userInfo['pid'];
            if (empty($goods['award_value'][$userInfo['role_id']]['num'][1])) continue;
            $val = $goods['award_value'][$userInfo['role_id']]['num'][1];

            if ($userInfo['role']['level'] == 1) {
                echo "会员积分" . $val . '<br>';
            } else if ($userInfo['role']['level'] == 2) {
                echo "代理" . $val . '<br>';
                $dailicount++;
            } else if ($userInfo['role']['level'] == 3) {
                $jc = 0;
                if ($dailicount > 0) {
                    $jc = empty($goods['award_value'][1]['num'][1]) ? 0 : $goods['award_value'][1]['num'][1];
                }
                $val = $val - intval($jc);
                echo "老板" . $val . '<br>';
            }
        } while ($parentId > 0);


        die;
        $orderInfo = OrderModel::find(120);
        dump((new OrderModel())->distribution($orderInfo, 'pay'));
        halt((new OrderModel())->distribution($orderInfo, 'add'));
        die;
        $user = UsersModel::where('user_id', 29936)->find();
        if (!empty($user) && !empty($user['pid'])) {
            $upUser = UsersModel::where(['user_id' => $user['pid']])->find();
            if ($upUser['role_id'] == 3 || $upUser['role_id'] == 0) {
                $pid = 0;
                do {

                    if (empty($upUser['pid'])) {
                        break;
                    }
                    $upUser = UsersModel::where(['user_id' => $upUser['pid'], 'role_id' => 1])
                        ->field('role_id,user_id,pid')->find();

                    if (!empty($upUser)) {
                        $pid = $upUser['user_id'];
                    }
                } while ($pid == 0);
                halt(UsersModel::where(['user_id' => $pid])->find());
            }
        }
    }

    /*
     * 直推代理
     */
    public function getUserzhituidailinum($user_id,$role_id){
        $where[] = ['pid','=',$user_id];
        $where[] = ['role_id','=',$role_id];
        $pushCount = UsersModel::where($where)->field('user_id')->select()->toArray();
        if($pushCount && !empty($pushCount)){
            return count($pushCount);
        }else{
            return 0;
        }
    }

    //清零抽奖次数
    public function qinglinprizetimes(){
        $key = input('key');
        if ($key !== 'fQ5dF8tA3xF6d001') die;
        //$users = Db::name("users")->where("prize_num > 0")->select();
        $users = Db::table("users")->where("1=1")->select();
        //dump($users);
        //$res = Db::table('users')->where('user_id',30701)->update(['roledaili'=>intval(4)]);
        //$res = Db::name('users')->where('user_id',30701)->data(['roledaili' => 5])->update();

        foreach ($users as $user) {
            $userss = UsersModel::where('user_id', $user['user_id'])->find();
            $res = Db::name('users')->where('user_id',$userss['user_id'])->update(['roledaili'=>$this->getUserzhituidailinum($userss['user_id'],1)]);
            //if($res){
            Db::name('users')->where('user_id',$userss['user_id'])->update(['prize_num'=>0]);
            //}



        }
        echo '执行完毕';
    }


    /*
     * 计划任务添加股东
     */
    public function getPutjiaquangudong(){
        $key = input('key');
        if ($key !== 'fQ5dF8tA3xF6d000') die;


        //$users = UsersModel::select();
        Db::name('jiaquangudong')->delete(true);

        $jcs = UsersLevelApplyModel::where($jcswhere)->select();
        if(count($jcs) == 0){
            echo "未开启奖金池分红" . PHP_EOL;
            exit;
        }

        foreach ($jcs as $key => $jc) {

            $users = UsersModel::select();
            foreach ($users as $user) {



                $additional_div = json_decode($user['additional_div'], true);
                $additional_div = intval($additional_div[$jc['level_id']]['value']);

                /*
                if(empty($additional_div) && $user['role_id']!==$jc['own_level']){
                    continue;
                }
                */
                $pushCount = UsersModel::where(['role_id' => $jc['push_level'], 'pid' => $user['user_id']])->field('user_id')->count();
                $pushCounts = $this->getUserzhituidailinum($user['user_id'],$jc['push_level']);


                $num = $pushCounts/$jc['push_num'];



                $num = intval($additional_div + $num);

                $divAmount = bcmul($amount, $num);

                $gudongData = [
                    'user_id' => $user['user_id'],
                    'zhituidailinum' => $this->getUserzhituidailinum($user['user_id'],$jc['push_level']),
                    'tuanduidailinum' => $this->getUserTuanduidailinum($user['user_id']),
                    'fene' => $num,
                    'level_apply_id' => $jc['level_id'],
                    'addtime' => time(),
                    'updatetime' => time(),
                ];
                $gudongres = Db::table("jiaquangudong")->where("user_id","=",$user['user_id'])->find();
                if($additional_div>0){
                    Db::table('jiaquangudong')->insert($gudongData);
                }
                if($pushCounts>=$jc['push_num'] && $num>0){
                    Db::table('jiaquangudong')->insert($gudongData);
                }



            }
        }
        echo "执行完毕" . PHP_EOL;
        exit;
    }

    /**
     * 获取用户下属ID集合
     * @param $uid int
     * @param $ids string
     * @author linkai
     * @return string
     */
    public function getUnderlingUIds($uid, $ids='')
    {
        $userModel = new UsersModel();
        //$back = Db("users")->field('user_id')->where('pid',$uid)->select();
        $back = Db::table("users")->field('user_id')->where("pid = ".$uid)->select();  //user_id != 30683 and
        if (!empty($back) && is_array($back)) {
            foreach ($back as $v) {
                //防止当前人的ID重复去查询，形成恶性循环
                if ($v['user_id'] == $uid) {
                    continue;
                }
                //$back2 = Db("users")->where('pid',$v['user_id'])->count('user_id');
                //$back22 = $userModel->field('user_id')->where('pid',$v['user_id'])->select();
                $back22 = Db::table("users")->field('user_id')->where("pid = ".$v['user_id'])->select();
                if ($back22 > 0) {

                    $ids = $this->getUnderlingUIds($v['user_id'],$ids);
                    $ids .= ','.$v['user_id'];
                    foreach ($back22 as $vs) {
                        $ids .= ','.$vs['user_id'];
                    }
                } else {
                    $ids .= ','.$v['user_id'];
                }
            }
        }
        $ids = $uid.','.$ids.',';
        $ids = str_replace(',,', ",", $ids);
        $ids = trim($ids, ',');
        return $ids;
    }

    /*
     * 获取团队下面几个代理
     *
     */
    public function getUserTuanduidailinum($uid){
        $usersArray = $this->getUnderlingUIds($uid);
        $wheres[] = ["role_id" , "=" , 1];
        $wheres[] = ["user_id" , "in" ,$usersArray];
        $userModel = new UsersModel();
        $isdaili = $userModel->where($wheres)->count();
        //echo Db('users','',false)->getLastSql();

        return $isdaili;
    }

    public function fenhong()
    {
        $key = input('key');
        if ($key !== 'fQ5dF8tA3xF6dE0q') die;
        $stage =date('Y').(intval(date('m')) -1);
        $date_str = '2023-10-01 00:00:00';
        $datetime = strtotime($date_str);
        $redaysss = Db::table('distribution_jc_execute_log')->where('1=1')->order('id desc')->find();
        $time = time();
        $starttime = $redaysss['create_time'];
        /*
        if($redaysss){
            $timesc = $redaysss['create_time'];
            $danqianday = ($time-$timesc)/(60 * 60 * 24);
            if($danqianday < 90){
                echo "上一次分红是".date("Y-m-d H:i:s",$timesc).'，三个月分红一次' . PHP_EOL;
                exit;
            }
        }else{
            $danqianday = ($time-$datetime)/(60 * 60 * 24);
            if($danqianday < 90){
                echo "上一次分红是".date("Y-m-d H:i:s",$datetime).'，三个月分红一次' . PHP_EOL;
                exit;
            }
        }
        */


        $execute = Db::table('distribution_jc_execute_log')->where('stage',$stage)->count();
        /*
        if ($execute) {
            echo "已执行" . PHP_EOL;
            die;
        }
        */

        if(empty($starttime)){
            $totalamounts = Db::table("distribution_jc_log")->where("1=1")->sum('enter_amount');

        }else{
            $amountwhere[] = ['createtime', '>', $starttime];
            $totalamounts = Db::table("distribution_jc_log")->where($amountwhere)->sum('enter_amount');
        }
        $jcswhere[] = ['num','>',0];
        $jcswhere[] = ['status','=',1];
        $jcs = UsersLevelApplyModel::where($jcswhere)->select();
        if(count($jcs) == 0){
            echo "未开启奖金池分红" . PHP_EOL;
            exit;
        }
        $DistributionLogModel = new DistributionLog();
        foreach ($jcs as $key => $jc) {
            $users = UsersModel::select();

            //$amount = $jc['total_amount'] / $jc['num'];
            $amount = $totalamounts / $jc['num'];
            $totalJoinNum = 0;
            $totalCopies = 0;
            $issueAmount = 0;
            foreach ($users as $user) {
                try {
                    $additional_div = json_decode($user['additional_div'], true);
                    $additional_div = intval($additional_div[$jc['level_id']]['value']);
                } catch (Exception $exception) {
                    continue;
                }
                if(empty($additional_div) && $user['role_id']!==$jc['own_level']){
                    continue;
                }
                //$pushCount = UsersModel::where(['role_id' => $jc['push_level'], 'pid' => $user['user_id']])->field('user_id')->count();
                //$num = $pushCount / $jc['push_num'];

                $pushCounts = $this->getUserzhituidailinum($user['user_id'],$jc['push_level']);


                $num = $pushCounts/$jc['push_num'];

                $num = intval($additional_div + $num);
                if ($num <= 0) continue;
                $divAmount = bcmul($amount, $num);
                $data = [
                    'jc_id' => $jc['level_id'],
                    'user_id' => $user['user_id'],
                    'num' => $num,
                    'stage' => $stage,
                    'total_amount' => $divAmount,
                    'additional' => empty($additional_div)?0:$additional_div,
                    'createtime' => time(),
                ];

                echo '用户：' . $user['nick_name'] . '  data:' . json_encode($data) . PHP_EOL;
                if($divAmount > 0){
                    $distrijunfenres = $DistributionLogModel->insert($data);
                }

                $AccountModel = new AccountModel();
                $changedata['change_desc'] = $jc['jc_name']."：奖金池分红：用户ID".$user['user_id'].",分红金额".$divAmount."元。";
                $changedata['change_type'] = 10;
                $changedata['by_id'] = 1;
                $changedata['from_uid'] = $user['user_id'];
                $changedata['balance_money'] = $divAmount;
                $changedata['bean_value'] = 0;
                $changedata['total_dividend'] = $divAmount;
                $changedata['md5log'] = $jc['jc_name']."：奖金池分红：用户ID".$user['user_id'].",分红金额:".$divAmount."元。";
                if($distrijunfenres && $divAmount > 0){
                    $AccountModel->change($changedata, $user['user_id'], false);
                }
                $totalCopies += $num;
                $totalJoinNum++;
                $issueAmount += $divAmount;
                //
            }


            $resss = Db::table('distribution_jc_execute_log')->where('1=1')->order('id desc')->find();
            if($resss){
                $yuefen = $resss['yuefen']+3;
            }else{
                $yuefen = 3;
            }
            $logData = [
                'total_amount' => $jc['total_amount'],
                'issue_amount' => $issueAmount,
                'total_copies' => $totalCopies,
                'total_join_num' => $totalJoinNum,
                'create_time' => time(),
                'stage' => $stage,
                'yuefen' => $yuefen,
            ];
            if($jc['total_amount']<$totalamounts){
                $jc->save(['total_amount' => 0]);
            }else{

                $jc->save(['total_amount' => $jc['total_amount']-$totalamounts]);
            }
            Db::table('distribution_jc_execute_log')->insert($logData);
            echo '奖池：' . $jc['jc_name'] . '  data:' . json_encode($logData) . PHP_EOL;
        }
        echo "执行完成" . PHP_EOL;
        die;


//        $goodsList = (new OrderGoodsModel)->where('order_id', 118)->select()->toArray();
//        halt($goodsList);
//        die;
//        $orderInfo = OrderModel::find(118);
//        halt((new OrderModel())->distribution($orderInfo, 'add'));
        //test script
        //分红开始
//        $orderInfo = OrderModel::find(76);
//        halt((new OrderModel())->distribution($orderInfo, 'add'));
//        $changedata['change_desc'] = '购物分返现';
//        $changedata['change_type'] = 3;
//        $changedata['integral_money'] = 100;
//        $res = (new AccountModel())->change($changedata, 29921, false);
//        halt($res);
    }
    /*------------------------------------------------------ */
    //-- 自定义商城首页
    /*------------------------------------------------------ */
    public function getIndexInfo()
    {


        $ShopPageTheme = new \app\jxcshop\model\ShopPageTheme();
        $data['page'] = $ShopPageTheme->getToWxApp();
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 自定义页页
    /*------------------------------------------------------ */
    public function getDiyPage()
    {
        $pageid = input('pageid', 0, 'intval');
        if ($pageid < 1) {
            return $this->error('传参错误.');
        }
        $ShopPageTheme = new \app\jxcshop\model\ShopPageTheme();
        $data['page'] = $ShopPageTheme->getToWxApp($pageid);
        return $this->success($data);
    }

    /*
    *加盟列表
    */
    public function getjiamenList(){
        $where[] = ['user_id','=',$this->userInfo['user_id']];
        $where[] = ['is_delete','=',0];
        $userModel = new UsersModel();

        $order = Db::table('shop_jiamen')->where($where)->limit(30)->order('id desc')->select();
        foreach ($order as $k=>$v){
            $order[$k]['addtime'] = date('Y-m-s h:i:s',$v['addtime']);
            if($v['level_id'] == 1){
                $order[$k]['level_idname'] = '区县代理';
            }else if($v['level_id'] == 2){
                $order[$k]['level_idname'] = '市级代理';
            }else if($v['level_id'] == 3){
                $order[$k]['level_idname'] = '省级代理';
            }else if($v['level_id'] == 4){
                $order[$k]['level_idname'] = '街道代理';
            }

        }
        $data['list'] = $order;
        //dump($data);
        return $this->success($data);
    }
}
